package tree;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.*;

/**
 * 107.二叉树的层次遍历 II
 *
 * @author Api
 * @date 2023/10/21 14:53
 */
public class Code107_HierarchicalTraversalOfBinaryTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {

        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> solution1(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return list;
        }
        queue.offerLast(root);
        while (!queue.isEmpty()) {
            List<Integer> levelList = new ArrayList<>();
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode peek = queue.peekFirst();
                levelList.add(queue.pollFirst().val);
                if (peek.left != null) {
                    queue.offerLast(peek.left);
                }
                if (peek.right != null) {
                    queue.offerLast(peek.right);
                }
            }
            list.add(levelList);
        }
        List<List<Integer>> result = new ArrayList<>();
        for (int i = list.size() - 1; i >= 0; i--) {
            result.add(list.get(i));
        }
        return result;
    }

    /**
     * 思路和模板相同, 对收集答案的方式做了优化, 最后不需要反转
     * 这个和102题很类似，无非在收集答案时，使用LinkedList收集
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        // 利用链表进行O(1)头部插入，这样最后答案不需要再反转了
        LinkedList<List<Integer>> ans = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ans.addFirst(temp);
        }
        return ans;
    }
}
